<!--
 * @Author: early-autumn
 * @Date: 2020-05-23 13:56:57
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-06 10:45:35
-->
<template>
  <div>
    <el-dialog
      :append-to-body="true"
      custom-class="dialog"
      width="1200px"
      :visible="value"
      @close="handleClose"
    >
      <div v-loading="loading">
        <el-timeline class="p20">
          <el-timeline-item timestamp="患者信息" placement="top">
            <el-card class="card" shadow="never">
              <el-link @click="handleDetails">
                <span class="card__name">{{ data.clinicPersonName }}</span>
                <el-tag class="card__name-tag" size="mini">
                  {{ patient.personStatus }}
                </el-tag>
              </el-link>
              <el-form label-width="100px" label-suffix="：" size="mini">
                <el-form-item class="card__form-item" label="预约门店">
                  {{ data.clinicName }}
                </el-form-item>
                <el-form-item class="card__form-item" label="病历号">
                  {{ patient.caseNumber }}
                </el-form-item>
                <el-form-item class="card__form-item" label="生日">
                  {{ patient.age }}岁
                </el-form-item>
                <el-form-item class="card__form-item" label="手机号">
                  {{ patient.phoneNumber }}
                </el-form-item>
                <el-form-item class="card__form-item" label="黄页编号">
                  {{ patient.yellowCode }}
                </el-form-item>
                <el-form-item class="card__form-item" label="初诊日期">
                  {{ patient.firstDiagnoseTime }}
                </el-form-item>
              </el-form>
            </el-card>
          </el-timeline-item>
          <el-timeline-item timestamp="预约信息" placement="top">
            <el-card class="card" shadow="never">
              <el-button
                class="card__position"
                type="primary"
                size="small"
                @click="handleAppointmentPanelVisible"
              >
                修改信息
              </el-button>
              <el-form label-width="100px" label-suffix="：" size="mini">
                <el-form-item class="card__form-item" label="预约时间">
                  <h2 style="margin: 0">{{ appointmentTime }}</h2>
                </el-form-item>
                <el-form-item class="card__form-item" label="现场TC">
                  {{ data.tcName }}
                </el-form-item>
                <el-form-item class="card__form-item" label="预约医生">
                  {{ data.doctorName }}
                </el-form-item>
                <el-form-item class="card__form-item" label="看诊项目">
                  {{ data.reservationProject }}
                </el-form-item>
                <el-form-item class="card__form-item" label="预约备注">
                  {{ data.remarks }}
                </el-form-item>
                <el-form-item class="card__form-item" label="创建时间">
                  {{ data.createTime }}
                </el-form-item>
                <el-form-item class="card__form-item" label="创建人">
                  {{ data.createBy }}
                </el-form-item>
              </el-form>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-divider></el-divider>
        <div class="p20">
          <!-- <template v-if="!data.onClinicTime">
            <el-button type="primary" @click="handleRegistered">
              到店挂号
            </el-button>
            <el-button type="primary" plain @click="delAppointment">
              取消预约
            </el-button>
          </template>
          <template v-else>
            <el-dropdown
              :class="data.appointmentStatus === 6 && 'disabled'"
              split-button
              type="primary"
              trigger="click"
              @click="handleCurrentStep(currentStep + 1, steps[currentStep])"
            >
              {{ steps[currentStep] }}
              <el-dropdown-menu slot="dropdown">
                <template v-for="(step, index) in steps">
                  <el-dropdown-item
                    v-if="status[index] !== 6"
                    :key="step"
                    :disabled="currentStep > index"
                    @click.native="handleCurrentStep(index + 1, step)"
                  >
                    {{ step }}
                  </el-dropdown-item>
                </template>
                <el-dropdown-item
                  :disabled="currentStep === 0"
                  @click.native="handleCurrentStep(currentStep - 1, '回退')"
                >
                  回退
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              style="margin-left: 10px;"
              type="primary"
              plain
              @click="handleAgainAppointment"
            >
              再次预约
            </el-button>
            <el-button type="primary" plain @click="handlePrintPanel">
              打印病历单
            </el-button>
          </template> -->
          <el-button type="primary" plain @click="handleSendMessage">
            短信提醒
          </el-button>
          <!-- <el-button type="primary" plain>查看日志</el-button> -->
        </div>
      </div>
    </el-dialog>
    <print-panel
      v-model="printPanelVisible"
      path="/print/makeCase"
      :data="patient"
    >
    </print-panel>
    <patient-editor-panel
      v-model="patientEditorPanelVisible"
      :default-patient="patient"
      @submit="handlePatientEditorPanelSubmit"
    ></patient-editor-panel>
    <send-message
      v-model="sendMessage.visible"
      :data="sendMessage.data"
    ></send-message>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getPerson } from '@/api/services/person'
import { delAppointment, updateAppointment } from '@/api/services/appointment'
import PrintPanel from '@/components/yiya/PrintPanel'
import SendMessage from '@/components/yiya/SendMessage'
import { encode } from '@/utils/utils'
import { PatientEditorPanel } from '../../components'

export default {
  name: 'AppointmentPatient',
  components: {
    PrintPanel,
    SendMessage,
    PatientEditorPanel,
  },
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => [],
    },
  },
  data() {
    return {
      // 加载中
      loading: false,
      // 患者
      patient: {},
      // 步骤
      steps: ['开始治疗', '完成治疗', '已经离开', '已经离开'],
      //
      status: [3, 4, 5, 6],
      // 当前步骤
      currentStep: 0,
      patientEditorPanelVisible: false,
      printPanelVisible: false,
      sendMessage: {
        visible: false,
        data: [],
      },
    }
  },
  computed: {
    // 预约时间
    appointmentTime() {
      const { startReservationTime, endReservationTime } = this.data
      return `${dayjs(startReservationTime).format('HH:mm')}-${dayjs(
        endReservationTime
      ).format('HH:mm')}`
    },
  },
  watch: {
    value(newVal) {
      if (newVal) {
        this.init()
      }
    },
  },
  methods: {
    init() {
      this.getPerson()
      const currentStep = this.status.indexOf(this.data.appointmentStatus)
      this.currentStep = currentStep === -1 ? 0 : currentStep
    },
    /**
     * 获取患者信息
     */
    async getPerson() {
      try {
        this.loading = true
        const { data } = await getPerson(this.data.clinicPersonId)
        this.patient = data
      } finally {
        this.loading = false
      }
    },
    /**
     * 查看按钮操作
     */
    handleDetails() {
      const menu = this.$route.path.slice(0, this.$route.path.lastIndexOf('/'))
      this.$router.push(
        `${menu}/details?id=${this.patient.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    /**
     * 关闭
     */
    handleClose() {
      this.$emit('close', false)
    },
    /**
     * 控制步骤
     */
    async handleCurrentStep(index, message) {
      if (index < 0 || index === this.status.length) {
        return
      }
      await this.$confirm(`${message}, 是否继续?`, '提示', { type: 'warning' })
      await this.updateAppointment({
        appointmentStatus: this.status[index],
      })
      this.currentStep = index
    },
    /**
     * 挂号
     */
    async handleRegistered() {
      if (this.patient.isTemporary === 0) {
        await this.$confirm('临时患者需要完善信息, 是否继续?', '提示', {
          type: 'warning',
        })
        this.patientEditorPanelVisible = true
      } else {
        await this.$confirm('到店挂号, 是否继续?', '提示', { type: 'warning' })
        await this.updateAppointment({
          clinicPersonName: this.patient.name,
          onClinicTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          appointmentStatus: 3,
          arriveClinic: this.clinicName,
        })
      }
    },
    /**
     * 修改预约信息
     */
    async updateAppointment(data) {
      await updateAppointment({ id: this.data.id, ...data })
      this.msgSuccess('修改成功')
      this.$emit('update')
      this.$emit('update:data', { ...this.data, ...data })
    },
    /**
     * 取消预约
     */
    delAppointment() {
      this.$confirm('取消预约, 是否继续?', '提示', { type: 'warning' }).then(
        async () => {
          await delAppointment(this.data.id)
          this.msgSuccess('取消成功')
          this.handleClose()
          this.$emit('update')
        }
      )
    },
    /**
     *
     */
    handleAppointmentPanelVisible() {
      const {
        id,
        clinicPersonId,
        clinicPersonName,
        reservationDate,
        doctorId,
        doctorName,
        tcId,
        tcName,
        startReservationTime,
        endReservationTime,
        reservationProject,
        remarks,
      } = this.data
      const data = {
        id,
        clinicPersonId,
        clinicPersonName,
        reservationDate,
        doctorId: +doctorId,
        doctorName,
        tcId: +tcId,
        tcName,
        startReservationTime,
        endReservationTime,
        remarks,
        reservationProject,
      }
      ;(data.reservationDate = dayjs(data.startReservationTime).format(
        'YYYY-MM-DD'
      )),
        this.handleClose()
      this.$emit('appointment-update', data, this.patient)
    },
    /**
     *
     */
    async handlePatientEditorPanelSubmit(form) {
      this.patient = form
      await this.handleRegistered()
    },
    /**
     * 再次预约
     */
    handleAgainAppointment() {
      console.log(this.patient)
      const {
        clinicPersonId,
        clinicPersonName,
        doctorId,
        doctorName,
        tcId,
        tcName,
      } = this.data
      const date = dayjs()
      const base = dayjs(
        `${date.format('YYYY-MM-DD HH')}:${Math.floor(date.minute() / 15) * 15}`
      )
      const data = {
        clinicPersonId,
        clinicPersonName,
        doctorId: +doctorId,
        doctorName,
        tcId: +tcId,
        tcName,
        reservationDate: date.format('YYYY-MM-DD'),
        startReservationTime: base.add(15, 'minute'),
        endReservationTime: base.add(45, 'minute'),
      }
      this.$emit('appointment-again', data, this.patient)
      this.handleClose()
    },
    /**
     * 打印病历单
     */
    handlePrintPanel() {
      this.printPanelVisible = true
    },
    handleSendMessage() {
      const { doctorName, reservationDate } = this.data
      const {
        id,
        name,
        phoneNumber,
        phoneOwnership,
        phoneNumber2,
        phoneOwnership2,
      } = this.patient
      this.sendMessage = {
        visible: true,
        data: [
          {
            id,
            phoneNumber,
            selectPhoneNumber: [
              {
                phoneNumber,
                phoneOwnership,
              },
              {
                phoneNumber: phoneNumber2,
                phoneOwnership: phoneOwnership2,
              },
            ],
            customerName: name,
            doctor: doctorName,
            time: reservationDate,
          },
        ],
      }
    },
  },
}
</script>

<style>
.dialog .el-dialog__body {
  padding: 20px 0 !important;
}

.disabled .el-button-group .el-button:first-child {
  background-color: #a0cfff;
  border-color: #a0cfff;
}
</style>

<style lang="scss" scoped>
.card {
  width: 100%;
  position: relative;

  .card__position {
    position: absolute;
    top: 15px;
    right: 15px;
    z-index: 2;
  }

  .card__name {
    margin-top: 0px;
    color: #1890ff;
    font-size: 20px;

    .card__name-tag {
      margin-left: 5px;
    }
  }

  .card__form-item {
    margin-bottom: 5px;
  }
}

.p20 {
  padding: 0 20px 0 35px;
}
</style>
